package com.pig4cloud.pig.consumer.controller;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/es")
public class ESController {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 根据“上升”字段进行分页查询 ES 索引 news_list_sharding
     *
     * @param page 页码，从 0 开始
     * @param size 每页数量
     * @return 查询结果列表
     * @throws IOException 当与 ES 通信发生错误时抛出
     */
    @GetMapping("/news")
    public List<Map<String, Object>> searchNewsByAscending(@RequestParam(defaultValue = "0") int page,
                                                           @RequestParam(defaultValue = "10") int size) throws IOException {
        // 创建搜索请求，指定索引为 news_list_sharding
        SearchRequest searchRequest = new SearchRequest("news_list_sharding");
        // 构建搜索源，设置查询条件和分页信息
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 查询所有文档
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        // 按“上升”字段升序排序
        //searchSourceBuilder.sort("上升", SortOrder.ASC);
        // 设置分页起始位置
        searchSourceBuilder.from(page * size);
        // 设置每页返回的文档数量
        searchSourceBuilder.size(size);
        // 将搜索源设置到搜索请求中
        searchRequest.source(searchSourceBuilder);

        // 执行搜索请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // 处理搜索结果
        List<Map<String, Object>> results = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            results.add(hit.getSourceAsMap());
        }
        return results;
    }
}